<template>
  <div class="chart-box">
    <el-row v-loading="chartLoading" class="sankey-row">
      <div
        ref="sankey"
        :id="'sankey-common' + random"
        style="width: 100%; height: 100%"
      ></div>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import nt from "../../../../../network";

let _ = import("lodash");
import mixinOption from "../../../../utils/mixinOption";
import parseApi from "../../../../utils/parseApi";

export default {
  name: "custom-report-component-chart-sankey",
  props: {
    api: {},
    method: {
      type: String,
      default: "get",
    },
    dataKey: {},
    mainTitle: {},
    componentData: {},
    changeSize: {},
    changeData: {},
    interval: {},
    time: {},
    mixinParam: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    chartData() {
      switch (this.dataKey) {
        case "common":
          return this.commonSankeyOption;
          break;
      }
    },
  },
  data() {
    return {
      comInterval: 0,
      chartLoading: false,
      isDataReady: false,
      random: Math.random(),
      commonSankeyData: {
        backgroundColor: "#FFFFFF",
        series: [
          {
            type: "sankey",
            left: 50.0,
            top: 20.0,
            right: 150.0,
            bottom: 25.0,
            data: [],
            links: [],
            lineStyle: {
              color: "source",
              curveness: 0.5,
            },
            itemStyle: {
              color: "#1f77b4",
              borderColor: "#1f77b4",
            },
            label: {
              color: "rgba(0,0,0,0.7)",
              fontFamily: "Arial",
              fontSize: 10,
            },
          },
        ],
        tooltip: {
          trigger: "item",
        },
      },
      commonSankeyOption: {},
    };
  },
  watch: {
    componentData() {
      this.changeStyle();
    },
    changeSize() {
      let chart = this.$echarts.init(
        document.getElementById("sankey-common" + this.random)
      );
      chart.resize();
    },
    "api.dsName": function () {
      this.getCommonSankeyData(this.changeStyle, true);
    },
    time() {
      this.changeParam();
    },
    mixinParam: {
      handler: function (val, oldVal) {
        let int = 0;
        int = setInterval(() => {
          if (!this.chartLoading) {
            clearInterval(int);
            this.changeParam();
          }
        }, 50);
      },
      deep: true,
    },
  },
  methods: {
    changeParam() {
      if (this.api) {
        this.getCommonSankeyData(this.changeStyle);
        clearInterval(this.comInterval);
        if (this.interval) {
          this.comInterval = setInterval(() => {
            this.getCommonSankeyData(this.changeStyle);
          }, this.interval * 1000);
        }
      }
    },
    getCommonSankeyData(callback, newApi) {
      this.chartLoading = true;
      let parseSankeyData = (data) => {
        let commonSankeyData = this.commonSankeyData;
        if (!data || JSON.stringify(data) === "{}") {
          data = {
            data: [
              {
                name: "",
                data: 0,
                unit: "",
              },
            ],
            links: [],
          };
        }
        let unit = data.data[0].unit || "";
        commonSankeyData.series[0].data = data.data.map((item, i) => {
          let length = this.componentData.color.length;
          return {
            name: item.name,
            value: item.data,
            itemStyle: {
              normal: {
                color: this.componentData.color[i % length],
                borderColor: this.componentData.color[i % length],
              },
            },
            tooltip: {
              formatter(arg) {
                return `${arg.name} : ${arg.value}  ${unit}`;
              },
            },
          };
        });
        commonSankeyData.series[0].links = data.links.map((item) => ({
          source: item.source,
          target: item.target,
          value: item.data,
        }));
        this.chartLoading = false;
        if (!this.isDataReady) {
          this.isDataReady = true;
          this.$emit( "dataReady");
        }
      };
      if (!this.api || !this.api.reqUrl) {
        let data = {
          data: [
            {
              //桑基图节点数据
              name: "节点1", //节点名称
              data: 15, //节点数据值，可不传，不传默认为links source为此name的value之和，例如此数据为5+3+3=11
              unit: "个", //label和tooltip单位，可不传
            },
            {
              name: "节点2",
            },
            {
              name: "节点3",
            },
            {
              name: "节点4",
            },
            {
              name: "节点5",
            },
            {
              name: "节点6",
            },
          ],
          links: [
            {
              //桑基图节点间链接数据
              source: "节点1", //此链接父节点名称，对应data内某项name
              target: "节点3", //此链接子节点名称，对应data内某项name
              data: 5, //此链接父子节点间流量数据
            },
            {
              source: "节点1",
              target: "节点4",
              data: 3,
            },
            {
              source: "节点2",
              target: "节点5",
              data: 8,
            },
            {
              source: "节点1",
              target: "节点5",
              data: 3,
            },
            {
              source: "节点5",
              target: "节点3",
              data: 1,
            },
            {
              source: "节点5",
              target: "节点6",
              data: 2,
            },
          ],
        };
        parseSankeyData(data);
        if (callback) {
          callback();
        }
      } else {
        nt.doRequest({
          method: "post",
          uri: "/paas/chart-layout/v1/compdsconfig/testCompDSConfig",
          data: parseApi({ api: this.api, mixinParam: this.mixinParam }),
          onSuccess: (resp) => {
            let data = resp.data.content.content;
            parseSankeyData(data);
            if (callback) {
              callback();
            }
          },
          onError: () => {
            parseSankeyData({});
            if (callback) {
              callback();
            }
          },
        });
      }
    },
    changeStyle() {
      let commonSankeyData = this.commonSankeyData;
      let componentData = this.componentData;
      commonSankeyData.color = componentData.color;
      for (let key in componentData.series[0]) {
        if (componentData.series[0].hasOwnProperty(key)) {
          commonSankeyData.series[0][key] = componentData.series[0][key];
        }
      }
      for (let key in componentData.grid) {
        if (componentData.grid.hasOwnProperty(key)) {
          commonSankeyData.series[0][key] = componentData.grid[key];
        }
      }
      if (componentData.colorByLev) {
        commonSankeyData.series[0].levels = [];
        componentData.color.forEach((colorItem, colorIndex) => {
          commonSankeyData.series[0].levels.push({
            depth: colorIndex,
            itemStyle: {
              color: colorItem,
              borderColor: colorItem,
            },
          });
        });
        commonSankeyData.series[0].data.forEach((item) => {
          delete item.itemStyle;
        });
      } else {
        delete commonSankeyData.series[0];
        let length = this.componentData.color.length;
        commonSankeyData.series[0].data.forEach((item, i) => {
          item.itemStyle = {
            normal: {
              color: this.componentData.color[i % length],
              borderColor: this.componentData.color[i % length],
            },
          };
        });
      }
      this.commonSankeyOption = _.cloneDeep(commonSankeyData);
      if (componentData.code) {
        //给开发人员测试的，怕忘记删，生产环境就不打印了
        process.env.NODE_ENV === "development" &&
          console.log(this.mainTitle + " 混入前option", commonSankeyData);
        this.commonSankeyOption = mixinOption(
          this.commonSankeyOption,
          componentData.code
        );
        process.env.NODE_ENV === "development" &&
          console.log(
            this.mainTitle + " 混入后option",
            this.commonSankeyOption
          );
      }
      let myChart = echarts.init(
        document.getElementById("sankey-common" + this.random)
      );
      myChart.setOption(this.commonSankeyOption);
      myChart.resize();
    },
  },
  mounted() {
    this.getCommonSankeyData(this.changeStyle);
    if (this.interval) {
      this.comInterval = setInterval(() => {
        this.getCommonSankeyData(this.changeStyle);
      }, this.interval * 1000);
    }
  },
  beforeDestroy() {
    clearInterval(this.comInterval);
  },
  emits: ["dataReady"],
};
</script>

<style scoped>
.chart-box {
  width: 100%;
  height: 100%;
  position: relative;
}
.sankey-row {
  width: 100%;
  height: 100%;
}
</style>
